package pub.guoxin.oops.manager.service.impl;

import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import pub.guoxin.oops.manager.service.DeviceDataInfoService;
import pub.guoxin.oops.model.DeviceDataInfo;
import pub.guoxin.oops.model.QDeviceDataInfo;
import pub.guoxin.oops.model.User;
import pub.guoxin.oops.repository.DeviceDataInfoRepository;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * Created by guoxin on 18-1-29.
 */
@Service
public class DeviceDataInfoServiceImpl implements DeviceDataInfoService {

    @Autowired
    private DeviceDataInfoRepository deviceDataInfoRepository;
    private QDeviceDataInfo q = QDeviceDataInfo.deviceDataInfo;

    @Override
    public Page<DeviceDataInfo> page(String sn, User user, LocalDateTime startTime, LocalDateTime endTime, Integer pageNumber, Integer pageSize) {
        BooleanExpression expression = q.used.isTrue();
        expression = expression.and(q.sn.eq(sn));
        if (Objects.nonNull(startTime)) {
            expression = expression.and(q.creation.goe(startTime));
            expression = expression.and(q.creation.loe(endTime));
        }

        Pageable request = new PageRequest(pageNumber - 1, pageSize, Sort.Direction.DESC, "creation");
        return deviceDataInfoRepository.findAll(expression, request);
    }

}
